package com.ky.manage.activity.aftersales;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ky.manage.R;
import com.ky.manage.activity.OrderListActivity;
import com.ky.manage.adapter.OrderMountingsAdapter;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.model.req.CreateOrderReq;
import com.ky.manage.model.response.CompanyInfoResp;
import com.ky.manage.model.response.MountingsResp;
import com.ky.manage.model.response.UserInfoResp;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import cz.msebera.android.httpclient.Header;

import static com.ky.manage.utils.http.BusinessHttpReqUtils.SERVICE_DOMAIN;

/**
 * 创建维修订单
 */
public class CreateMaintainOrderActivity extends BaseActivity implements OrderMountingsAdapter.MoountingsCountListner {

    //订单创建请求实体对象
    CreateOrderReq orderReq = new CreateOrderReq();
    //订单中的配件
    List<CreateOrderReq.Mountings> orderMountingsList = new ArrayList<>();
    UserInfoResp mUserInfoResp;
    TextView tvAddress, tvNetPointName, tvCreateOrder, tvTotalPrice, tvRepairPrice, tvMountingsTotalPrice;
    EditText etvUserName, etvUserPhone;
    ListView listView;
    OrderMountingsAdapter adapter;
    View layoutMountings;
    RadioGroup gpRepairType, gpIsWarrantyUser;
    //0 在保  1 不在保
    int isWarranty = 0;
    //0 零件损坏   1其它
    int repairTpye = 0;
    double totalPrice = 0, mountingsPrice, repairPrice;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_maintain_order;
    }

    @Override
    protected void initView() {
        findTextView(R.id.page_title_tv, "维修订单");
        findView(R.id.back_iv, v -> {
            finish();
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        //收货地址
        tvAddress = findView(R.id.tv_select_address);
        tvAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(CreateMaintainOrderActivity.this, ManagerAddressActivity.class), 101);
            }
        });
        //网点名称
        tvNetPointName = findView(R.id.tv_netPoint_name);

        adapter = new OrderMountingsAdapter(this, new ArrayList<>(), this);
        listView = findView(R.id.lv_mountings_list);
        listView.setAdapter(adapter);

        layoutMountings = findView(R.id.layout_mountings);
        gpRepairType = findView(R.id.rg_modify_type);
        gpRepairType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_mountings) {
                    repairTpye = 0;
                    layoutMountings.setVisibility(View.VISIBLE);
                    repairPrice = 0;
                    tvRepairPrice.setText("¥" + repairPrice);
                    totalPrice -= 50; //维修类型零件损坏， 维修费用0  加配件费用
                    totalPrice += mountingsPrice;
                    tvMountingsTotalPrice.setText("¥" + mountingsPrice);
                    tvTotalPrice.setText("¥" + totalPrice);
                } else if (checkedId == R.id.rb_others) {
                    repairTpye = 1;
                    layoutMountings.setVisibility(View.GONE);
                    repairPrice = 50;
                    tvRepairPrice.setText("¥" + repairPrice);
                    tvMountingsTotalPrice.setText("¥0");
                    totalPrice += repairPrice; //维修类型其它， 维修费用50  无配件费用
                    totalPrice -= mountingsPrice;
                    tvTotalPrice.setText("¥" + totalPrice);
                }
            }
        });
        gpIsWarrantyUser = findView(R.id.rg_zaibao);
        gpIsWarrantyUser.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_zaibao_yes) {
                    isWarranty = 0;
                } else {
                    isWarranty = 1;
                }
            }
        });
        etvUserName = findView(R.id.etv_username);
        etvUserPhone = findView(R.id.etv_userphone);

        tvCreateOrder = findView(R.id.tv_create_order);
        tvCreateOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendOrder();
            }
        });

        tvTotalPrice = findView(R.id.tv_total_price);
        tvMountingsTotalPrice = findView(R.id.tv_mountings_total_price);
        tvRepairPrice = findView(R.id.tv_repair_price);
    }

    @Override
    protected void initData() {
        orderReq = new CreateOrderReq();
        requestLoginUserInfo();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            tvAddress.setText(data.getStringExtra("address"));
        }
    }

    //获取登录用户信息
    public void requestLoginUserInfo() {
        BusinessHttpReqUtils.getInstance().requestLoginUserInfo(this, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                mUserInfoResp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, UserInfoResp.class);
                if (mUserInfoResp != null && mUserInfoResp.code == 200) {
                    Log.d("lhm", "getUserInfo = " + mUserInfoResp.toString());
                    Log.d("lhm", "getUserInfo = " + responseString);

                    tvNetPointName.setText(mUserInfoResp.data.businessOutletsName);
                    //requestGetMountingsListForNetPoint();
                    requestDeptByOutlets(mUserInfoResp.data.businessOutletsId);
                }
            }
        });
    }

    //根据deptId获取配件列表
    public void requestGetMountingsListForDept(int deptId) {
        RequestParams httpParams = new RequestParams();
        httpParams.put("deptId", deptId);
        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/appApi/getMountingsList", httpParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm", "getMountingsForNetPoint fail = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "getMountingsForNetPoint success= " + responseString);
                MountingsResp mountingsResp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, MountingsResp.class);
                if (mountingsResp != null && mountingsResp.getCode() == 200) {
                    adapter.setData(mountingsResp.getRows());
                }
            }
        });
    }

    //根据OutletsId获取deptId
    public void requestDeptByOutlets(int businessOutletsId) {

        RequestParams httpParams = new RequestParams();
        httpParams.put("businessOutletsId", businessOutletsId);

        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/appApi/getCompanyInfo", httpParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm", "requestDeptByCompanyInfo fail = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "requestDeptByCompanyInfo success= " + responseString);
                CompanyInfoResp resp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, CompanyInfoResp.class);
                if (resp != null && resp.getCode() == 200) {
                    requestGetMountingsListForDept(resp.getData().getDeptId());
                }
            }
        });
    }

    @Override
    public void OnAddition(int count, MountingsResp.RowsDTO obj) {
        Log.d("lhm", obj.getMountingsName() + " OnAddition = " + count);
        //totalPrice -= mountingsPrice;
        mountingsPrice += obj.getUnitPrice();
        tvMountingsTotalPrice.setText("¥" + mountingsPrice);
        totalPrice += obj.getUnitPrice();
        tvTotalPrice.setText("¥" + totalPrice);
        moutingsCountChange(count, obj);
    }

    @Override
    public void OnMinus(int count, MountingsResp.RowsDTO obj) {
        Log.d("lhm", obj.getMountingsName() + " OnMinus = " + count);
        //totalPrice -= mountingsPrice;
        //零件总金额
        mountingsPrice -= obj.getUnitPrice();
        tvMountingsTotalPrice.setText("¥" + mountingsPrice);
        //订单总金额
        totalPrice -= obj.getUnitPrice();
        tvTotalPrice.setText("¥" + totalPrice);
        moutingsCountChange(count, obj);
    }

    private void moutingsCountChange(int count, MountingsResp.RowsDTO obj) {
        CreateOrderReq.Mountings mountings = orderReq.new Mountings();
        mountings.setMountingsId(obj.getMountingsId());
        mountings.setMountingsName(obj.getMountingsName());
        mountings.setUnitPrice(obj.getUnitPrice());
        boolean isContains = false;
        if (orderMountingsList.size() > 0) {
            Iterator<CreateOrderReq.Mountings> mountingsIterator = orderMountingsList.iterator();
            while (mountingsIterator.hasNext()) {
                CreateOrderReq.Mountings mountings1 = mountingsIterator.next();
                if (obj.getMountingsId() == mountings1.getMountingsId()) {
                    isContains = true;
                    if (count == 0) {
                        mountingsIterator.remove();
                    } else {
                        mountings1.setAmount(count);
                    }
                    break;
                } else {
                    isContains = false;
                }
            }
            if (!isContains) { //不包含当前配件对象  新增到list
                mountings.setAmount(count);
                orderMountingsList.add(mountings);
            }
        } else {
            mountings.setAmount(count);
            orderMountingsList.add(mountings);
        }
    }

    //创建订单请求
    private void sendOrder() {
        String userName = etvUserName.getText().toString();
        String userPhone = etvUserPhone.getText().toString();
        String userAddress = tvAddress.getText().toString();
        orderReq.setClientName(userName);
        orderReq.setClientTel(userPhone);
        orderReq.setTakeAddress(userAddress);
        orderReq.setIsWarrantyUser(isWarranty);
        orderReq.setRepairType(repairTpye);
        orderReq.setGoodsCount(orderMountingsList.size());
        //orderReq.setGoodsPrice(0.01);
        orderReq.setGoodsPrice(mountingsPrice);
        orderReq.setRepairPrice(repairPrice);
        orderReq.setVisitPprice(0);
        orderReq.setMountingsVoList(orderMountingsList);
        orderReq.setNetPointId(mUserInfoResp.data.businessOutletsId);
        //orderReq.setNetPointName(mUserInfoResp.data.businessOutletsName);
        orderReq.setNetPointName(12321);


        if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(userName) ||TextUtils.isEmpty(userName)) {
            ToastUtils.showToast("请完整填写信息后再提交订单！");
            return;
        }
        JSONObject jsonObject = null;
        try {
            String json = new Gson().toJson(orderReq);
            Log.d("lhm", "sendOrder json = " + json);
            jsonObject = new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        AsyncHttpUtils.getInstance().postJson(this, SERVICE_DOMAIN + "/appApi/addOrder", jsonObject, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "create order response = " + responseString);
                ToastUtils.showToast("订单创建成功，前往订单支付页面");
                startActivity(new Intent(CreateMaintainOrderActivity.this, OrderListActivity.class));
            }
        });

    }
}
